from public import getResultDf, getAnalysis
from spice.circuit import Circuit


# 电容反接判断
def against(circuit: Circuit, net:str, initial:str)->list[str]:
    select = []
    cdt = {}
    if not circuit: return ['未上传网表信息']
    for component in circuit.component_map.values():
        if all((component.name.startswith('C'), 
               component.info.part_name  == 'CP',
               len(component.point)==2)):
            if component.point[1].symbol!='0': select.append(f'V({component.point[1].symbol})')
            if component.point[2].symbol!='0': select.append(f'V({component.point[2].symbol})')
            cdt[component.symbol] = (component.point[1].symbol, component.point[2].symbol)
    if not select: return []
    df, log, _ = getResultDf(net, getAnalysis('.tran 0.1ms 100ms', initial), select)
    if df is None: return [f'电容反接分析失败\n{log[-500:]}']
    err = []
    i = 0
    zerocs = []
    for c, p12 in cdt.items():
        if p12[0]=='0':
            ls1 = [0]*df.shape[0]
        else:
            ls1 = df.iloc[:, i*2+1]
            i+=1
        if p12[1]=='0':
            ls2 = [0]*df.shape[0]
        else:
            ls2 = df.iloc[:, i*2+1]
            i+=1   
        is_zero = True
        for v1,v2 in zip(ls1, ls2):
            if v1!=0 or v2!=0: is_zero=False
            if v1<v2:
                err.append(f'{c} 极性电容存在正负极反接情况')
                break
        if is_zero: zerocs.append(c)
    if zerocs: err.append(f'{", ".join(zerocs)} 极性电容两端电压均为0, 请设置实际初始条件或添加模拟电源再进行校验')
    return err
        